<template>
  <div class="app-container">
    <div class="uploadInfo">
      <h3>{{ $t('operateStep') }}</h3>
      <div class="left" style="margin-top: 20px; padding: 0 60px 70px 70px; width: 80%">
        <el-steps :active="stepValue">
          <el-step :title="$t('warehouseStep.stepOne')" :description="$t('warehouseStep.stepOneDesc')" />
          <el-step :title="$t('warehouseStep.stepThree')" :description="$t('warehouseStep.stepThreeDesc')" />
          <el-step :title="$t('warehouseStep.stepFour')" :description="$t('warehouseStep.stepFourDesc')" />
          <el-step :title="$t('warehouseStep.stepFive')" :description="$t('warehouseStep.stepFiveDesc')" />
          <el-step :title="$t('warehouseStep.stepSix')" :description="$t('warehouseStep.stepSixDesc')" />
        </el-steps>
      </div>
    </div>
    <!-- 普通打印 -->
    <!--    <vue-easy-print-->
    <!--      v-show="isShow"-->
    <!--      ref="easyPrintBoxGeneral"-->
    <!--      table-show-->
    <!--      :one-page-row="onePageRow"-->
    <!--    >-->
    <!--      &lt;!&ndash;      <div class="skuHead" style="text-align: left">&ndash;&gt;-->
    <!--      &lt;!&ndash;        <h2>Express</h2>&ndash;&gt;-->
    <!--      &lt;!&ndash;      </div>&ndash;&gt;-->
    <!--      <vue-barcode-->
    <!--        line-color="#000"-->
    <!--        display-value="true"-->
    <!--        format="CODE128"-->
    <!--        font="bold"-->
    <!--        :value="queryParams.containerCode"-->
    <!--        text-align="center"-->
    <!--        text-position="bottom"-->
    <!--        text-margin="5"-->
    <!--        font-size="26"-->
    <!--        height="60"-->
    <!--        width="2"-->
    <!--        class="barCode"-->
    <!--      />-->
    <!--    </vue-easy-print>-->
    <div class="goodsInfo">
      <div class="left" style="width: 80%">
        <h3>{{ $t('msgEnter') }}</h3>
        <el-form
          ref="form"
          :rules="rules"
          :model="queryParams"
          label-suffix=":"
          label-width="120px"
        >
          <el-form-item prop="originalBox">
            <el-checkbox v-model="checked" @change="changeBox">{{ $t("warehousingLang.OriginalBoxStorage") }}</el-checkbox>
          </el-form-item>
          <el-form-item prop="returnNumber" :label="$t('returnLang.returnDocNo')">
            <el-input
              ref="input"
              v-model.lazy="queryParams.returnNumber"
              :placeholder="$t('pleaseScan') + $t('returnLang.returnDocNo')"
              style="width: 40%"
              @keyup.enter.native="getByReturnNo"
            />
          </el-form-item>
          <el-form-item prop="skuCode" :label="$t('goodsSKULang.skuCode')">
            <el-input
              ref="skuCode"
              v-model.lazy="queryParams.skuCode"
              :placeholder="$t('pleaseScan') + $t('goodsSKULang.skuCode')"
              :disabled="skuDisabled"
              style="width: 40%"
              @keyup.enter.native="getSkuCodeInfo"
            />
          </el-form-item>
          <el-form-item prop="skuNum" :label="$t('goodsSKULang.skuNum')">
            <el-input
              v-if="readonly === false"
              v-model.number="queryParams.skuNum"
              type="number"
              :placeholder="$t('pleaseEnter')"
              :readonly="readonly"
              style="width: 40%"
            />
            <div v-else class="el-input-scan">
              <span>{{ queryParams.skuNum }} </span>
            </div>
            <el-button
              v-if="readonly === true"
              type="primary"
              round
              size="mini"
              style="position: absolute; margin-left: 5px"
              @click="changeToInputMode"
            >
              {{ $t("statusLang.changeToInputMode") }}</el-button>
            <el-button
              v-else
              type="primary"
              round
              size="mini"
              style="position: absolute; margin-left: 5px"
              @click="changeToScanMode"
            >
              {{ $t("statusLang.changeToScanMode") }}</el-button>
          </el-form-item>
          <el-form-item
            prop="packagingType"
            :label="$t('unitLang.weight') + $t('unitLang.size')"
          >
            <el-table :data="queryParams.weightSizeData" border>
              <el-table-column
                prop="inStockType"
                align="center"
                :label="$t('warehousingLang.warehousingType')"
                min-width="80"
              >
                <template v-slot="{ row }">
                  <div :class="row.inStockType === 0 ? 'active' : ''">
                    <span>{{ row.inStockType === 0 ? $t("warehousingLang.firstArrival") : $t("warehousingLang.toTheWarehouseAgain") }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="skuCode"
                align="center"
                :label="$t('goodsSKULang.skuCode')"
                min-width="80"
              />
              <el-table-column
                align="center"
                min-width="100"
                prop="packagingType"
              >
                <template slot="header">
                  <i style="color: #f56c6c; margin-right: 5px">*</i>
                  <span>{{ $t("warehousingLang.packageType") }}</span>
                </template>
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'weightSizeData.' + scope.$index + '.packagingType'"
                    :rules="{
                      required: true,
                      message: $t('pleaseSelect'),
                      trigger: 'change',
                    }"
                  >
                    <el-select
                      v-model="scope.row.packagingType"
                      :placeholder="$t('pleaseSelect')"
                    >
                      <el-option
                        v-for="item in packageTypeOptions"
                        :key="item.value"
                        :value="item.value"
                        :label="$t('warehousingLang.' + item.title)"
                      />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="skuWeight"
                align="center"
                :label="$t('unitLang.weight') + '(KG)'"
                min-width="90"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'weightSizeData.' + scope.$index + '.skuWeight'"
                    :rules="{
                      required: true,
                      message: $t('pleaseEnter'),
                      trigger: 'blur',
                    }"
                  >
                    <el-input
                      v-model.number="scope.row.skuWeight"
                      type="number"
                      :placeholder="$t('pleaseEnter') + $t('unitLang.weight')"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="skuLength"
                align="center"
                :label="$t('unitLang.length') + '(CM)'"
                min-width="90"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'weightSizeData.' + scope.$index + '.skuLength'"
                    :rules="{
                      required: true,
                      message: $t('pleaseEnter'),
                      trigger: 'blur',
                    }"
                  >
                    <el-input
                      v-model.number="scope.row.skuLength"
                      type="number"
                      :placeholder="$t('pleaseEnter') + $t('unitLang.length')"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="skuWidth"
                align="center"
                :label="$t('unitLang.width') + '(CM)'"
                min-width="90"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'weightSizeData.' + scope.$index + '.skuWidth'"
                    :rules="{
                      required: true,
                      message: $t('pleaseEnter'),
                      trigger: 'blur',
                    }"
                  >
                    <el-input
                      v-model.number="scope.row.skuWidth"
                      type="number"
                      :placeholder="$t('pleaseEnter') + $t('unitLang.width')"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="skuHeight"
                align="center"
                :label="$t('unitLang.height') + '(CM)'"
                min-width="90"
              >
                <template v-slot="scope">
                  <el-form-item
                    :prop="'weightSizeData.' + scope.$index + '.skuHeight'"
                    :rules="{
                      required: true,
                      message: $t('pleaseEnter'),
                      trigger: 'blur',
                    }"
                  >
                    <el-input
                      v-model.number="scope.row.skuHeight"
                      type="number"
                      :placeholder="$t('pleaseEnter') + $t('unitLang.height')"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
        <el-row type="flex" justify="start">
          <el-button
            type="primary"
            style="width: 20%; margin-left: 120px"
            @click="handleSubmit"
          >{{ $t("submit") }}</el-button>
        </el-row>
      </div>
      <div class="right" style="width: 20%">
        <h3>{{ this.$t("harvestLang.backList") + " : " }}</h3>
        <el-table :data="tableData" border>
          <el-table-column
            :label="$t('tableIndex')"
            type="index"
            align="center"
            width="55"
          />
          <el-table-column
            :label="$t('goodsSKULang.skuCode')"
            align="center"
            prop="skuCode"
            min-width="120"
          />
          <el-table-column
            :label="$t('goodsSKULang.forecastQuantity')"
            align="center"
            prop="skuNum"
            min-width="100"
          />
        </el-table>
      </div>
    </div>
    <div class="uploadInfo">
      <h3>{{ $t('backOrderLang.msgUp') }}</h3>
      <div style="margin-top: 20px; padding: 0 10px 50px 50px">
        <el-row type="flex" justify="start">
          <el-button type="primary" @click="handleUpload">{{
            $t("upload")
          }}</el-button>
          <el-button type="warning" plain @click="deleteSelectItem">{{
            $t("delete")
          }}</el-button>
        </el-row>
        <el-table
          ref="multipleTable"
          :data="uploadInfoData"
          tooltip-effect="dark"
          class="mt-10"
          border
          size="mini"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" align="center" min-width="20" />
          <el-table-column
            :label="$t('tableIndex')"
            align="center"
            type="index"
            width="55px"
          />
          <el-table-column
            :label="$t('returnLang.returnDocNo')"
            min-width="120"
            prop="returnNumber"
            align="center"
          />
          <el-table-column
            prop="skuCode"
            :label="$t('goodsSKULang.skuCode')"
            min-width="120"
            align="center"
          />
          <el-table-column
            :label="$t('warehousingLang.receiptQuantity')"
            prop="skuNum"
            min-width="80"
            align="center"
          />
          <el-table-column
            prop="skuWeight"
            :label="$t('unitLang.weight') + '(KG)'"
            min-width="120"
            align="center"
          />
          <el-table-column
            prop="skuLength"
            :label="$t('unitLang.length') + '(CM)'"
            min-width="120"
            align="center"
          />
          <el-table-column
            prop="skuWeight"
            :label="$t('unitLang.width') + '(CM)'"
            min-width="120"
            align="center"
          />
          <el-table-column
            prop="skuHeight"
            :label="$t('unitLang.height') + '(CM)'"
            min-width="120"
            align="center"
          />
          <el-table-column
            prop="operator"
            :label="$t('goodsSKULang.operator')"
            min-width="80"
            align="center"
          />
          <el-table-column
            prop="operationDate"
            :label="$t('operationDate')"
            min-width="80"
            align="center"
          />
        </el-table>
      </div>
      <div
        ref="autoPrint"
        style="position: absolute; z-index: -9; bottom: 60px; left: 80px;"
      >
        <vue-barcode
          line-color="#000"
          display-value="true"
          format="CODE128"
          font="bold"
          :value="queryParams.containerCode"
          text-align="center"
          text-position="bottom"
          text-margin="5"
          font-size="26"
          height="60"
          width="2"
          class="barCode"
        />
      </div>
    </div>
  </div>
</template>

<script>
import to from 'await-to-js'
import VueBarcode from 'vue-barcode'
// import vueEasyPrint from 'vue-easy-print'
import { packageTypeDict } from '@/utils/dictData'
import { getDictOptionList } from '@/utils/dictUtils'
import {
  getContainerByContainerCodeNew, returnEnterDivide, skuScan, skuScanNew
} from '@/api/business/warehouseManage/warehousing'
import { getByReturnNo } from '@/api/business/operateManage/return'
import { downloadPDF } from '@/utils/pdf'
import { scanFail, scanSuccess } from '@/utils/validate'
export default {
  components: { VueBarcode },
  data() {
    return {
      stepValue: 0,
      checked: false,
      userInfo: {
        userName: null,
        userId: null
      },
      onePageRow: 5,
      isShow: false,
      containerId: null,
      returnNumber: null,
      skuId: null,
      readonly: true,
      containerDisabled: false,
      skuDisabled: false,
      queryParams: {
        originalBox: 0,
        returnNumber: '',
        containerCode: '',
        skuCode: null,
        skuNum: 0, // sku 入库数量
        weightSizeData: [] // 重量尺寸数据
      },
      tableData: [], // 装箱清单数据
      uploadInfoData: [], // 上传
      data: [], // 操作成功
      multipleSelection: [], // el-table多选选中的值
      packageTypeDict: packageTypeDict,
      packageTypeOptions: getDictOptionList(packageTypeDict),
      rules: {}
    }
  },
  created() {
    this.userInfo = this.$store.state.user.userMsg
  },
  mounted() {
    this.$refs.input.focus()
  },
  methods: {
    autoPrint() {
      this.$nextTick(() => {
        downloadPDF(this.$refs.autoPrint);
      })
    },
    changeBox(val) {
      this.queryParams.originalBox = +val
    },
    // 扫描退件单号
    async getByReturnNo() {
      const { data } = await getByReturnNo({
        returnNo: this.queryParams.returnNumber,
        originalBox: this.queryParams.originalBox
      })
      if (!data) {
        scanFail()
      }
      scanSuccess()
      this.tableData = data.orderSkuBOList
      this.stepValue = 1
      if (data.containerCode && data.containerCode !== null) {
        this.queryParams.containerCode = data.containerCode
        this.containerId = data.containerId
        this.returnNumber = this.queryParams.returnNumber
        this.skuDisabled = false
        // 自动打印
        if (this.queryParams.containerCode) {
          this.$nextTick(() => {
            // this.$refs.easyPrintBoxGeneral.print()
            this.autoPrint()
          })
        }
      }
      this.containerDisabled = false
      setTimeout(() => {
        this.$refs.containerCode.focus()
      }, 100)
    },
    // 扫描流转箱号
    async getContainerCodeInfo() {
      try {
        this.queryParams.skuCode = null
        const { data } = await getContainerByContainerCodeNew({
          containerCode: this.queryParams.containerCode
        })
        this.containerId = data.containerId
        if (data.containerStatus === 1) {
          scanFail()
          this.$message.error(this.$t('warehousingLang.scanBoxTip'))
          return
        }
        scanSuccess()
        this.skuDisabled = false
        setTimeout(() => {
          this.$refs.skuCode.focus()
        }, 100)
      } catch (e) {
        scanFail()
        return
      }
    },
    // 扫描sku
    async getSkuCodeInfo() {
      // 先判断前后扫描的sku是否一致，如果不一致提示用户
      if (this.queryParams.weightSizeData.length !== 0) {
        // 不一致
        if (this.queryParams.skuCode !== this.queryParams.weightSizeData[0].skuCode) {
          this.$alert(this.$t('warehousingLang.SKUInconsistency') + this.$t('pleaseRescan'), this.$t('hint'),
            {
              confirmButtonText: this.$t('confirm'),
              callback: (action) => {
                this.$message({
                  type: 'info',
                  message: `action: ${action}`
                })
                this.queryParams.skuCode = null
              }
            }
          )
        } else {
          // sku 一致继续扫描 件数加1
          this.queryParams.skuCode = null
          this.queryParams.skuNum++
          scanSuccess()
        }
      } else {
        try {
          const res = await skuScanNew({
            orderType: 'RETURN',
            skuCode: this.queryParams.skuCode,
            containerCode: this.queryParams.containerCode,
            orderNo: this.queryParams.returnNumber
          })
          scanSuccess()
          const arr = []
          arr.push(res.data)
          this.skuId = res.data.skuId
          this.queryParams.weightSizeData = arr
          this.queryParams.skuNum++
          // 判断流转箱是否绑定
          if (this.uploadInfoData.length !== 0) {
            for (let i = 0; i < this.uploadInfoData.length; i++) {
              const arr = this.uploadInfoData[i]
              if (arr.containerCode === this.queryParams.containerCode) {
                // sku不一致 提示用户流转箱已绑定
                if (this.queryParams.skuCode !== arr.skuCode) {
                  scanFail()
                  this.$alert(
                    this.$t('containerTypeLang.container') +
                    this.queryParams.containerCode +
                    this.$t('statusLang.Bound') +
                    this.$t('warehousingLang.pleaseReplaceTheFlowBox'),
                    this.$t('hint'),
                    {
                      confirmButtonText: this.$t('confirm'),
                      callback: (action) => {
                        this.$message({
                          type: 'info',
                          message: `action: ${action}`
                        })
                        this.queryParams.containerCode = null
                        this.queryParams.weightSizeData = []
                        this.queryParams.skuNum = 0
                      }
                    }
                  )
                  // 流转箱已绑定，重新扫描流转箱sku
                  return
                } else {
                  const res = await skuScanNew({
                    orderType: 'RETURN',
                    skuCode: this.queryParams.skuCode,
                    containerCode: this.queryParams.containerCode,
                    orderNo: this.queryParams.returnNumber
                  })
                  scanSuccess()
                  const arr = []
                  arr.push(res.data)
                  this.queryParams.weightSizeData = arr
                  this.skuId = res.data.skuId
                  this.queryParams.skuCode = null
                }
                return
              }
            }
          } else {
            const res = await skuScan({ skuCode: this.queryParams.skuCode })
            const arr = []
            arr.push(res.data)
            this.queryParams.weightSizeData = arr
            this.skuId = res.data.skuId
            this.queryParams.skuCode = null
          }
          this.queryParams.skuCode = null
        } catch (error) {
          scanFail()
          return
        }
      }
    },
    // 提交
    async handleSubmit() {
      const [err] = await to(this.$refs.form.validate())
      if (err === null) {
        // 判断预报数量与入库数量是否一致
        for (let i = 0; i < this.tableData.length; i++) {
          const tempArr1 = this.tableData[i]
          for (let j = 0; j < this.queryParams.weightSizeData.length; j++) {
            const tempArr2 = this.queryParams.weightSizeData[j]
            if (tempArr1.skuCode === tempArr2.skuCode) {
              if (this.queryParams.skuNum <= tempArr1.skuNum) {
                console.log('测试1')
                if (this.queryParams.skuNum === tempArr1.skuNum) {
                  console.log('直接提交')
                } else if (this.queryParams.skuNum < tempArr1.skuNum) {
                  // 判断sku 数量是否大于预报数量，
                  const flag = await this.$confirm(
                    'sku:' +
                      tempArr1.skuCode +
                      this.$t(
                        'warehousingLang.preSkuNumIsInconsistentWithReceiptQuantity'
                      ) +
                      this.$t('warehousingLang.pleaseConfirmWhetherToUpload') +
                      '?',
                    this.$t('hint'),
                    {
                      confirmButtonText: this.$t('confirm'),
                      cancelButtonText: this.$t('cancel'),
                      type: 'warning'
                    }
                  ).catch((err) => err)
                  if (flag === 'cancel') {
                    this.$message({
                      type: 'info',
                      message: this.$t('warehousingLang.cancelUpload')
                    })
                    return
                  } else {
                    this.$message({
                      type: 'success',
                      message: this.$t(
                        'warehousingLang.subjectToTheWarehousingQuantity'
                      )
                    })
                  }
                }
              } else if (this.queryParams.skuNum > tempArr1.skuNum) {
                this.$message({
                  type: 'success',
                  // message: this.$t(
                  //   "warehousingLang.subjectToTheWarehousingQuantity"
                  // ),
                  message: 'sku 入库数量 大于预报数量请重新输入或扫描'
                })
              }
              console.log(this.uploadInfoData, '测试3')
              // 判断如果提交栏中已经有箱号 流转箱 sku 相同的值 skuNum 相加
              let index = -1
              this.uploadInfoData.forEach((item, i) => {
                const arr1 = item
                const arr2 = this.queryParams
                if (
                  arr1.returnNumber === arr2.returnNumber &&
                  arr1.skuCode === arr2.weightSizeData[0].skuCode &&
                  arr1.containerCode === arr2.containerCode
                ) {
                  index = i
                  this.uploadInfoData[i].skuNum += arr2.skuNum
                }
              })
              // indx = -1 sku containerCode boxNumber 都不匹配 直接加一条
              if (index === -1) {
                console.log(this.queryParams, 'this.queryParams')
                this.uploadInfoData.push({
                  containerCode: this.queryParams.containerCode,
                  inStockType: this.queryParams.weightSizeData[0].inStockType,
                  packagingType: this.queryParams.weightSizeData[0].packagingType,
                  returnNo: this.queryParams.returnNumber,
                  skuCode: this.queryParams.weightSizeData[0].skuCode,
                  skuHeight: this.queryParams.weightSizeData[0].skuHeight,
                  skuLength: this.queryParams.weightSizeData[0].skuLength,
                  skuNum: this.queryParams.skuNum,
                  skuWeight: this.queryParams.weightSizeData[0].skuWeight,
                  skuWidth: this.queryParams.weightSizeData[0].skuWidth,
                  returnNumber: this.queryParams.returnNumber,
                  // skuId: this.skuId,
                  // containerId: this.containerId,
                  operationDate: new Date().toLocaleString(),
                  operator: this.userInfo.userName
                })
              }
              this.checked = false
              this.queryParams = {
                returnNumber: null,
                containerCode: null,
                skuCode: null,
                skuNum: 0,
                weightSizeData: []
              }
              this.containerDisabled = true
              this.skuDisabled = true
            }
          }
        }
        console.log(this.multipleSelection, 'this.multipleSelection')
        this.$refs.input.focus()
        this.tableData = []
      } else {
        this.$message.error({
          message: this.$t('warehousingLang.pleaseComplete')
        })
      }
    },
    // 上传
    async handleUpload() {
      if (this.multipleSelection.length > 0) {
        const res = await returnEnterDivide({ enterReqList: this.uploadInfoData })
        if (res.returnCode === 10000) {
          this.$message({
            type: 'success',
            message: this.$t('warehousingLang.uploadSuccess')
          })
          this.$refs.input.focus()
          this.uploadInfoData = []
          this.tableData = []
        }
      } else {
        this.$message({
          type: 'warning',
          message: this.$t('pleaseSelect')
        })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(val)
    },
    // 删除
    deleteSelectItem() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: this.$t('pleaseSelect')
        })
        return
      }
      this.$confirm(this.$t('delete') + '?', this.$t('hint'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(() => {
          this.multipleSelection.forEach((value, index) => {
            this.uploadInfoData.forEach((v, i) => {
              if (
                value.boxNumber === v.boxNumber &&
                value.containerCode === v.containerCode &&
                value.skuCode === v.skuCode
              ) {
                this.uploadInfoData.splice(i, 1)
              }
            })
          })
          this.$message({
            type: 'success',
            message: this.$t('deleteSuccess')
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('cancel')
          })
        })
    },
    changeToInputMode() {
      this.readonly = !this.readonly
    },
    changeToScanMode() {
      this.readonly = !this.readonly
    }
  }
}
</script>

<style lang="scss" scoped>
.goodsInfo {
  display: flex;
  justify-content: space-between;
}
.active {
  color: red;
}
.el-input-scan {
  width: 40%;
  height: 36px;
  line-height: 36px;
  font-size: 16px;
  background-color: #f59a23;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 0 15px;
}
.barCode {
  image-rendering: -webkit-optimize-contrast; /* Safari */
  image-rendering: crisp-edges; /* Firefox */
  image-rendering: pixelated; /* Chrome */
}
</style>

<style>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
</style>
